<template>
  <div>
    <el-row>
      <el-col :span="20">
        <div>
          <el-button type="primary" @click="dialogFormVisible = true">创建课程</el-button>
          <el-button v-if="exportFlag === 0" type="primary" @click="getExportActivity">导出课程信息</el-button>
          <el-button v-else-if="exportFlag === 1" disabled type="primary">正在导出...</el-button>
          <el-button v-else type="success" @click="download">下载课程信息</el-button>
        </div>
      </el-col>
      <el-col :span="4">
        <div style="text-align: right">
          <el-input placeholder="请输入课程名称" v-model="activitySearch" class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
          </el-input>
        </div>
      </el-col>
    </el-row>
    <div style="margin-top: 10px;">
      <el-table :data="activityViewList" style="width: 100%;" border :empty-text="loadingFlag === true ? '正在拼命加载中...':'暂无数据'">
        <el-table-column prop="activityLogo" label="封面" width="260">
          <template slot-scope="scope">
            <el-image style="width: 100%; height: 180px" :src="mediaHost + scope.row.activityLogo"
                      fit="cover"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="activityName" label="课程名称" width="150"></el-table-column>
        <el-table-column prop="activityType" label="课程类型" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.activityType === 1">前端开发</span>
            <span v-else-if="scope.row.activityType === 2">后端开发</span>
            <span v-else-if="scope.row.activityType === 3">移动开发</span>
            <span v-else-if="scope.row.activityType === 4">前沿技术</span>
            <span v-else-if="scope.row.activityType === 5">运维技术</span>
            <span v-else-if="scope.row.activityType === 6">测试技术</span>
            <span v-else>其他技术</span>
          </template>
        </el-table-column>
        <el-table-column prop="activityDesc" label="课程描述" width="240"></el-table-column>
        <el-table-column prop="createTimeStr" label="创建时间" width="150"></el-table-column>
        <el-table-column prop="activityContentNum" label="课件数量" width="80"></el-table-column>
        <el-table-column prop="authNum" label="报名人数" width="80"></el-table-column>
        <el-table-column align="right" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleStudent(scope.$index, scope.row)">学 员
            </el-button>
            <el-button
              size="mini"
              @click="handleContent(scope.$index, scope.row)">课 件
            </el-button>
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编 辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="canDeleteActivity(scope.$index, scope.row)">删 除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--请求标识-->
      <div v-if="loadingFlag=== true" style="text-align: center;font-size: larger;margin-top: 10px;">
        <i  class="el-icon-loading"></i>
      </div>
      <div v-else-if="activityPage.hasMore === true" style="text-align: center;font-size: small;color: #99a9bf;margin-top: 10px;" @click="loadingMore()">
        <span>--点击加载更多--</span>
      </div>
      <div v-else-if="activityViewList.length > 0" style="text-align: center;font-size: small;color: #99a9bf;margin-top: 10px;">
        <span>--没有更多数据了--</span>
      </div>
    </div>
    <!--创建课程-->
    <el-dialog title="创建课程" :visible.sync="dialogFormVisible" width="30%" :before-close="closeDialog"
               :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="activityView">
        <el-form-item label="课程名称">
          <el-input type="text" placeholder="请输入课程名称" v-model="activityView.activityName" autocomplete="off"
                    maxlength="20" show-word-limit/>
        </el-form-item>
        <div>
          <span>课程类型</span>
        </div>
        <el-form-item style="margin-top: 10px;">
          <el-select v-model="activityView.activityType" placeholder="请选择课程类型">
            <el-option label="前端开发" :value="1"></el-option>
            <el-option label="后端开发" :value="2"></el-option>
            <el-option label="移动开发" :value="3"></el-option>
            <el-option label="前沿技术" :value="4"></el-option>
            <el-option label="运维技术" :value="5"></el-option>
            <el-option label="测试技术" :value="6"></el-option>
            <el-option label="其他技术" :value="7"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程描述">
          <el-input type="textarea" placeholder="请输入课程描述" v-model="activityView.activityDesc" maxlength="100"
                    show-word-limit/>
        </el-form-item>
      </el-form>
      <div>
        <div>
          <span>设置封面</span>
        </div>
        <label for="fileInput">
          <el-image v-if="activityLogoUrl !== this.$global.avatar" fit="cover" :src="this.$global.mediaHost + this.activityLogoUrl"
                    style="margin-top: 15px;height: 150px; width: 270px;">
          </el-image>
          <el-image v-else-if="activityId !== ''" fit="cover"
                    :src="this.$global.mediaHost + this.activityView.activityLogo"
                    style="margin-top: 15px;height: 150px; width: 270px;">
          </el-image>
          <el-image v-else fit="contain" :src="this.$global.mediaHost + this.$global.avatar"
                    style="margin-top: 15px;height: 150px; width: 150px;">
          </el-image>
        </label>
        <input v-show="false" type="file" id="fileInput" accept="image/*" @change="uploadImage">
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary"
                   @click="activityId == null || activityId === '' ? createActivity() : updateActivity()">
          {{ activityId == null || activityId === '' ? '创 建' : '修 改' }}
        </el-button>
      </div>
    </el-dialog>

    <!--删除提示框-->
    <el-dialog title="提示" :visible.sync="deleteDialogVisible" width="20%">
      <span>确认删除此课程吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteActivity()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "MyActivity",
  data() {
    return {
      mediaHost: this.$global.mediaHost,
      activityViewList: [],
      activityPage: this.$global.indexPage,
      activitySearch: '',
      paramsData: {
        page: this.activityPage,
        activitySearch: this.activitySearch
      },
      loadingFlag: false,
      dialogFormVisible: false,
      deleteDialogVisible: false,
      activityId: '',
      activityView: {
        activityId: '',
        activityName: '',
        activityType:'',
        activityDesc: '',
        activityLogo: this.$global.avatar,
      },
      activityLogoUrl:this.$global.avatar,
      formLabelWidth: '80px',
      exportFlag : 0,
      downloadUrl: '',
    }
  },
  mounted() {
    addEventListener('scroll', this.handleScroll)//监听函数
  },
  methods: {
    handleScroll() {
      //变量scrollTop是滚动条滚动时，距离顶部的距离
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      //变量windowHeight是可视区的高度
      let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
      //变量scrollHeight是滚动条的总高度
      let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
      //滚动条到底部的条件
      if (scrollTop + windowHeight === scrollHeight) {
        //你想做的事情
        if (this.activityPage.hasMore === true && !this.loadingFlag) {
          this.activityPage.page += 1;
          this.getMyActivityList();
        }
      }
    },
    loadingMore:function () {
      this.activityPage.page += 1;
      this.getMyActivityList();
    },
    download:function () {
      this.exportFlag = 0;
      window.open(this.mediaHost + this.downloadUrl, '_blank')
    },
    /**
     * 我的课程列表
     */
    getMyActivityList: function () {
      this.loadingFlag = true
      this.paramsData.page = this.activityPage
      this.paramsData.activityType = null
      this.paramsData.activitySearch = this.activitySearch
      this.$ajax({
        method: 'post',
        headers: this.$global.headers,
        url: this.$global.host + '/v1/activity/getMyActivityList',
        data: JSON.stringify({
          "data": this.paramsData,
          "user": this.$global.getUser(),
          "teamId": this.$global.getTeamId()
        }),
      }).then(response => {
        const responseData = response.data.data;
        const responseState = response.data.state
        if (2000 === responseState.code) {
          this.loadingFlag = false
          this.activityViewList = this.activityViewList.concat(responseData.pageData.data)
          this.activityPage = responseData.pageData.page
        } else {
          this.$message.error({
            message: responseState.msg,
            center: true,
            duration: 1000
          });
        }
      }).catch(function (err) {
        console.log(err)
      })
    },
    /**
     * 导出课程信息
     */
    getExportActivity: function () {
      this.$message.success({
        message: "正在导出，请稍后",
        center: true,
        duration: 1000
      });
      this.exportFlag = 1
      this.paramsData = {}
      this.$ajax({
        method: 'post',
        headers: this.$global.headers,
        url: this.$global.host + '/v1/activity/getExportActivity',
        data: JSON.stringify({
          "data": this.paramsData,
          "user": this.$global.getUser(),
          "teamId": this.$global.getTeamId()
        }),
      }).then(response => {
        const responseData = response.data.data;
        const responseState = response.data.state
        if (2000 === responseState.code) {
          this.exportFlag = 2
          this.downloadUrl = responseData.downloadUrl
          this.$message.success({
            message: "数据导出成功，请点击按钮下载",
            center: true,
            duration: 1000
          });
        } else {
          this.exportFlag = 0
          this.$message.error({
            message: responseState.msg,
            center: true,
            duration: 1000
          });
        }
      }).catch(function (err) {
        console.log(err)
      })
    },
    /**
     * 查找
     */
    search: function () {
      this.activityPage = this.$global.indexPage
      this.activityViewList = []
      this.getMyActivityList()
    },
    uploadImage: function (e) {
      if (e.target.files[0] !== undefined) {
        let fileName = e.target.files[0].name;
        let fileType = e.target.files[0].type;
        let imageType = this.$global.imageType
        if (!fileType.includes(imageType)) {
          this.$message.warning({
            message: "文件类型错误",
            center: true,
            duration: 1000
          });
          return false;
        }
        fileName = "/"+ imageType +"/" + this.$global.randomStr(24) + fileName.substring(fileName.lastIndexOf("."))
        const OSS = require('ali-oss')
        const client = new OSS({
          bucket: this.$global.bucket,
          region: this.$global.region,
          secure: true,
          accessKeyId: this.$global.accessKeyId,
          accessKeySecret: this.$global.accessKeySecret,
        });
        const asyncThis = this
        async function put () {
          try {
            let loading = asyncThis.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading'
            });
            //object-name可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
            await client.put(fileName, e.target.files[0]);
            loading.close();
            asyncThis.activityLogoUrl = fileName;
          } catch (e) {
            console.log(e);
          }
        }
        put();
      }
    },
    createActivity: function () {
      if (this.checkInput()) {
        this.dialogFormVisible = false
        this.paramsData.activityName = this.activityView.activityName
        this.paramsData.activityType = this.activityView.activityType
        this.paramsData.activityDesc = this.activityView.activityDesc
        this.paramsData.activityLogoUrl = this.activityLogoUrl
        this.$ajax({
          method: 'post',
          headers: this.$global.headers,
          url: this.$global.host + '/v1/activity/createActivity',
          data: JSON.stringify({
            "data": this.paramsData,
            "user": this.$global.getUser(),
            "teamId": this.$global.getTeamId()
          }),
        }).then(response => {
          const responseData = response.data.data;
          const responseState = response.data.state
          if (2000 === responseState.code) {
            this.$message.success({
              message: "开课成功",
              center: true,
              duration: 1000
            });
            this.deleteData()
            this.closeDialogDeleteData()
            this.getMyActivityList()
          } else {
            this.$message.error({
              message: responseState.msg,
              center: true,
              duration: 1000
            });
          }
        }).catch(function (err) {
          console.log(err)
        })
      }
    },
    updateActivity: function () {
      if (this.checkInput()) {
        this.dialogFormVisible = false
        this.paramsData.activityId = this.activityId
        this.paramsData.activityName = this.activityView.activityName
        this.paramsData.activityType = this.activityView.activityType
        this.paramsData.activityDesc = this.activityView.activityDesc
        if (this.activityLogoUrl === this.$global.avatar) {
          this.paramsData.activityLogoUrl = ""
        } else {
          this.paramsData.activityLogoUrl = this.activityLogoUrl
        }
        this.$ajax({
          method: 'post',
          headers: this.$global.headers,
          url: this.$global.host + '/v1/activity/updateActivity',
          data: JSON.stringify({
            "data": this.paramsData,
            "user": this.$global.getUser(),
            "teamId": this.$global.getTeamId()
          }),
        }).then(response => {
          const responseData = response.data.data;
          const responseState = response.data.state
          if (2000 === responseState.code) {
            this.$message.success({
              message: "更新课程信息成功",
              center: true,
              duration: 1000
            });
            this.deleteData()
            this.closeDialogDeleteData()
            this.getMyActivityList()
          } else {
            this.$message.error({
              message: responseState.msg,
              center: true,
              duration: 1000
            });
          }
        }).catch(function (err) {
          console.log(err)
        })
      }
    },
    detail: function () {
      this.paramsData.activityId = this.activityId
      this.$ajax({
        method: 'post',
        headers: this.$global.headers,
        url: this.$global.host + '/v1/activity/detail',
        data: JSON.stringify({
          "data": this.paramsData,
          "user": this.$global.getUser(),
          "teamId": this.$global.getTeamId()
        }),
      }).then(response => {
        const responseData = response.data.data;
        const responseState = response.data.state
        if (2000 === responseState.code) {
          this.activityView = responseData.activityView
        } else {
          this.$message.error({
            message: responseState.msg,
            center: true,
            duration: 1000
          });
        }
      }).catch(function (err) {
        console.log(err)
      })
    },

    /**
     *
     * 判断是否确认删除课程
     * @param index
     * @param row
     */
    canDeleteActivity(index, row) {
      this.deleteDialogVisible = true
      this.deleteActivityId = row.activityId
    },
    /**
     * 删除课程
     */
    deleteActivity() {
      this.deleteDialogVisible = false
      this.paramsData.activityId = this.deleteActivityId
      this.$ajax({
        method: 'post',
        headers: this.$global.headers,
        url: this.$global.host + '/v1/activity/deleteActivity',
        data: JSON.stringify({
          "data": this.paramsData,
          "user": this.$global.getUser(),
          "teamId": this.$global.getTeamId()
        }),
      }).then(response => {
        const responseData = response.data.data;
        const responseState = response.data.state
        if (2000 === responseState.code) {
          this.$message.success({
            message: "删除课程成功",
            center: true,
            duration: 1000
          });
          this.deleteData()
          this.getMyActivityList()
        } else {
          this.$message.error({
            message: responseState.msg,
            center: true,
            duration: 1000
          });
        }
      }).catch(function (err) {
        console.log(err)
      })
    },

    cancel: function () {
      this.dialogFormVisible = false
      this.closeDialogDeleteData()
    },
    closeDialog: function (done) {
      this.closeDialogDeleteData()
      done();
    },
    closeDialogDeleteData: function () {
      this.activityId = ''
      this.activityView.activityId = ''
      this.activityView.activityName = ''
      this.activityView.activityType = ''
      this.activityView.activityDesc = ''
      this.activityView.activityLogo = this.$global.avatar
      this.activityLogoUrl = this.$global.avatar
    },
    deleteData: function () {
      this.activityViewList = []
      this.activityPage = this.$global.indexPage
    },
    handleStudent: function (index, row) {
      this.$router.push({path: "/homePage/student", query: {activityId: row.activityId + ""}})
    },
    handleContent: function (index, row) {
      this.$router.push({path: "/homePage/activityContent", query: {activityId: row.activityId + ""}})
    },
    handleEdit: function (index, row) {
      this.dialogFormVisible = true
      this.activityId = row.activityId
      this.detail()
    },
    checkInput:function () {
      if (!this.$global.checkSpecificKey(this.activityView.activityName)) {
        this.$message.warning({
          message: '不允许输入特殊符号',
          center: true,
          duration: 1000
        });
        return false
      }
      if (this.activityView.activityName === '') {
        this.$message.warning({
          message: "请输入课程名称",
          center: true,
          duration: 1000
        });
        return false
      }
      if (this.activityView.activityType === '') {
        this.$message.warning({
          message: "请选择课程类型",
          center: true,
          duration: 1000
        });
        return false
      }
      if (this.activityView.activityDesc === '') {
        this.$message.warning({
          message: "请适当的描述课程内容",
          center: true,
          duration: 1000
        });
        return false
      }
      if (this.activityId === '' && this.activityLogoUrl === this.$global.avatar) {
        this.$message.warning({
          message: "请选择课程Logo",
          center: true,
          duration: 1000
        });
        return false
      }
      return true
    }
  },
  created() {
    this.getMyActivityList()
  }
}
</script>

<style scoped>
.el-select .el-input {
  width: 130px;
}

.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
</style>
